<?php

namespace app\index\controller;

use app\admin\model\TieComments;
use app\common\controller\Frontend;
use app\common\model\Category;
use http\Exception;
use think\Controller;
use think\Request;
use app\admin\model\Tie as TieModel;
use app\admin\model\User;
use app\admin\model\TieLike;

class Tie extends Frontend
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = 'default';

    // 帖子详情
    public function detail($id){
        $tie = TieModel::with(['user','comment'])->where(['tie.id' => $id])->find();
        $tie->hits = $tie->hits + 1;
        if (!$tie->save())
            $this->error();
        $tie['tie_num'] = TieComments::where(['topic_id' => $tie['id']])->count();
        $tie['category'] = Category::get(['id' => $tie['category_id']]);
        foreach ($tie['comment'] as $item){
            $item['user'] = User::get(['id' => $item['user_id']]);
        }

        $this->assign(array(
            'title' => '帖子详情',
            'tie' => $tie,
            'uid' => $this->auth->id
        ));
        return $this->view->fetch();
    }

    //评论
    public function comment(){
        $res = TieComments::create($_POST);
        if (!$res)
            return json(['code' => 0, 'msg' => '评论失败']);
        return json(['code' => 1, 'msg' => '评论成功']);
    }

    //点赞
    public function like(){
        $like = TieLike::get(['user_id' => $_POST['user_id'], 'topic_id' => $_POST['topic_id']]);
        $tie = TieModel::get(['id' => $_POST['topic_id']]);
        if (!$like){
            $res = TieLike::create($_POST);
            $tie->likenum = $tie->likenum + 1;
        }else{
            $res = TieLike::destroy($like['id']);
            $tie->likenum = $tie->likenum - 1;
        }
        if (!$tie->save())
            return json(['code' => 0, 'msg' => '操作失败']);
        if (!$res)
            return json(['code' => 0, 'msg' => '操作失败']);
        return json(['code' => 1, 'msg' => '操作成功']);
    }

}
